package com.example.server.db


import com.example.server.db.tables.AppVersions
import com.example.server.db.tables.Articles
import com.example.server.db.tables.Users
import io.ktor.server.application.*
import kotlinx.coroutines.Dispatchers
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.StdOutSqlLogger
import org.jetbrains.exposed.sql.addLogger
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.sql.transactions.transaction

object DatabaseFactory {

    internal fun init() {
//        println(File(".").absolutePath)
        val driverClassName = "org.h2.Driver"
        // 嵌入db:file后面跟db绝对路径
        val jdbcURL = "jdbc:h2:file:./db/db2;AUTO_SERVER=TRUE"
        val database = Database.connect(jdbcURL, driverClassName)
        transaction(database) {
            addLogger(StdOutSqlLogger)

//            SchemaUtils.create(Articles, Users)
            SchemaUtils.createMissingTablesAndColumns(
                Articles,
                Users,
                AppVersions
            )
        }
    }

    suspend fun <T> dbQuery(block: suspend () -> T): T =
        newSuspendedTransaction(Dispatchers.IO) { block() }
}

fun Application.configDb() {
    DatabaseFactory.init()
}